package com.io.convert;

import java.io.*;

/**
 * 编码与解码（乱码问题）
 *
 * @author jiangbang
 * @date 2016/6/2
 */
public class ConverDemo1 {

    public static void main(String[] args) {
        try {
            test3();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void test2(){
        String str = "中国"; //gbk
        //解码char -->byte
        byte[] data = str.getBytes();
        System.out.println(new String(data,0,3));
    }

    /**
     * 编码与解码字符集必须相同，否则乱码
     * @throws UnsupportedEncodingException
     */
    public static void test1() throws UnsupportedEncodingException {
        //解码 byte -->char
        String str = "中国"; //gbk
        //解码char -->byte
        byte[] data = str.getBytes();
        //编码和解码字符集同一
        System.out.println(data);
        data = str.getBytes("utf-8");//设置编码字符集
        //不同一出现乱码
        System.out.println(new String(data));

        //编码
        byte[] data2 = "中国".getBytes("utf-8");
        //解码
        str = new String(data2,"utf-8");
        System.out.println(str);
    }

    /**
     *   转换流：字节转为字符
     * 1.输出流：outputStreamWriter  编码
     * 2.输入流：inputStreamReader 解码
     */
    public static void test3() throws IOException {
        //指定解码
        BufferedReader br = new BufferedReader(
                new InputStreamReader( new FileInputStream(new File("D:/demo/1.txt")),"utf-8"));

        //写出文件
        BufferedWriter bw = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(new File("D:/demo/2.txt")),"utf-8"));
        String info = null;
        while (null!=(info=br.readLine())){
            System.out.println(info);
        }
        br.close();

    }

}
